<template>
  <div class="ab">
    <div class="btn">
      <el-input class="search" placeholder="文件名" prefix-icon="el-icon-search" v-model="keywords">
      </el-input>
    </div>
    <el-table :data="searchResults" style="width: 100%" max-height="350">
      <el-table-column prop="dname" label="文件名" width="400">
      </el-table-column>
      <el-table-column prop="dsize" label="文件大小" width="400">
      </el-table-column>
      <el-table-column prop="ctime" label="创建日期" width="500">
      </el-table-column>
      <el-table-column fixed="right" label="操作" width="120">
        <template #scope="scope">
          <a :href="`/ky/user/download?dname=${scope.row.dname}`">下载</a>
        </template>
      </el-table-column>
    </el-table>
    <div class="block">
      <span class="demonstration">分页选择</span>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage" :page-sizes="[10]"
                     :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="fileTotal">
      </el-pagination>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import axios from 'axios';

const route = useRoute();

const keywords = ref('');
const fileList = ref([]);
const searchResults = ref([]);
const currentPage = ref(1);
const pageSize = ref(10);
const fileTotal = ref(0);

const search = (keywords) => {
  const newList = [];
  fileList.value.forEach((item) => {
    if (item.dname.indexOf(keywords) !== -1) {
      newList.push(item);
    }
  });
  return newList;
};

const handleSizeChange = (val) => {
  pageSize.value = val;
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  querydata();
};

const querydata = async () => {
  try {
    const response = await axios.get(`/ky/user/subjectfiles?sid=${route.query.id}&currentPage=${currentPage.value}`);
    const result = response.data;
    fileList.value = result.data.list;
    fileTotal.value = result.data.total;
    searchResults.value = search(keywords.value);
  } catch (error) {
    console.error('请求数据出错:', error);
  }
};

watch(keywords, () => {
  searchResults.value = search(keywords.value);
});

watch(() => route.query.id, () => {
  currentPage.value = 1;
  querydata();
});

onMounted(() => {
  querydata();
});
</script>

<style scoped>
.btn {
  width: 100%;
  background-color: #fff;
}

.search {
  width: 300px;
  margin-left: 100px;
  margin-top: 10px;
}
</style>